package container.map;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * http://blog.csdn.net/sunxianghuang/article/details/52221913
 * http://www.educity.cn/java/498061.html
 * 阅读 ConcurrentSkipListMap
 */
public class T05_ConcurrentHashMap {
    public static void main(String[] args) {
        // TreeMap
        // Map<String, String> map = new HashMap<>(); // Collections.synchronizedXXX
        // Map<String, String> map = new Hashtable<>();
        // Map<String, String> map = new ConcurrentSkipListMap<>(); // 高并发并且排序
        Map<String, String> map = new ConcurrentHashMap<>();

        Random r = new Random();
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);
        long start = System.currentTimeMillis();
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    map.put("a" + r.nextInt(100000), "a" + r.nextInt(100000));
                }
                latch.countDown();
            });
            threads[i].start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("time: " + (end - start));
        System.out.println("size: " + map.size());
    }
}
